//
//  ChannelAddViewController.m
//  History
//
//  Created by Jam on 16/9/10.
//  Copyright © 2016年 kane. All rights reserved.
//

#import "ChannelAddViewController.h"
#import "NewsListCell.h"
#import "MJRefresh.h"
#import "FilterContentView.h"
#import "ContentViewController.h"

@interface ChannelAddViewController ()<UITableViewDataSource,UITabBarDelegate,UISearchBarDelegate,NewsListCellDelegate,MJRefreshBaseViewDelegate,ContentViewDelegate>
{
    
    __weak IBOutlet UIView *topView;
    __weak IBOutlet UISearchBar *searchBar;
    __weak IBOutlet UITableView *contentTable;
    __weak IBOutlet UIImageView *headImageView;
    __weak IBOutlet UILabel *subjectLabel;
    __weak IBOutlet UIButton *addBtn;
    __weak IBOutlet UIButton *shareBtn;
    NSMutableArray *newsList;
    
    MJRefreshHeaderView *header;
    EmptyView *emptyView;
    FilterContentView *_filterView;
}

@end

@implementation ChannelAddViewController
@synthesize dataInfo;
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    newsList = [NSMutableArray array];
    addBtn.layer.cornerRadius = 5;
    addBtn.layer.borderColor = [UIColor whiteColor].CGColor;
    addBtn.layer.borderWidth = .5f;
    shareBtn.layer.cornerRadius = 5;
    shareBtn.layer.borderColor = [UIColor whiteColor].CGColor;
    shareBtn.layer.borderWidth = .5f;
    subjectLabel.text = dataInfo[@"channel_name"];
    searchBar.text = dataInfo[@"channel_name"];
    addBtn.selected = NO;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeNightMode) name:kChangeNightMode object:nil];
    [self changeNightMode];
    [self initRefreshUI];
}

-(void)changeNightMode
{
    topView.backgroundColor = KKColor_Black_White;
}

- (void)initRefreshUI
{
    header = [MJRefreshHeaderView header];
    header.scrollView = contentTable;
    header.delegate = self;
    header.hidden = YES;
    [header beginRefreshing];
}

- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    NSDictionary *params = @{@"cs_cid":[[UserEntity sharedUser] getUserID],@"a_channelid":[dataInfo[@"channel_id"] convertToString],@"a_status":@""};
    [WebService findArticleList:params WithBlock:^(id result, NSError *error) {
        if (!error) {
            if ([result[@"errcode"] integerValue] == 0) {
                NSArray *dataAry = result[@"result"][@"article"][@"value"];
                [newsList removeAllObjects];
                [newsList addObjectsFromArray:dataAry];
                [contentTable reloadData];
            }
        }
        [refreshView endRefreshing];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma tableviewDelegate

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return newsList.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *item = newsList[indexPath.row];
    NSString *imgString = [item[@"a_picture"] convertToString];
    NSArray *photoAry = [imgString componentsSeparatedByString:@","];
    NSInteger type = 0;
    if (photoAry.count >= 3) {
        type = 3;
    }else if (photoAry.count >= 1){
        type = 1;
    }
    switch (type) {
        case 0:
            return 85;
            break;
        case 1:
            return 90;
            break;
        case 3:
            return 170;
            break;
        default:
            break;
    }
    return 0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"HomeClassCell";
    NewsListCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[NewsListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.dataIndex = indexPath.row;
    cell.delegate = self;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSDictionary *dict = newsList[indexPath.row];
    [cell setupNewsData:dict];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *dict = newsList[indexPath.row];
    ContentViewController *content = [[ContentViewController alloc] init];
    content.dataInfo = dict;
    [self.navigationController pushViewController:content animated:YES];
}

#pragma mark - UIScrollView Delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [searchBar resignFirstResponder];
    CGFloat offsetY = scrollView.contentOffset.y;
    for (int i = 0; i < 4; i++) {
        UIView *headerContentView = contentTable.tableHeaderView.subviews[i];
        headerContentView.transform = CGAffineTransformMakeTranslation(0, MIN(offsetY, 0));
    }
}

#pragma mark - NewListCellDelegate
- (void)clickFilterButton:(NSInteger)index withCGRect:(CGRect)rect
{
    if(!_filterView){
        _filterView = [[[UINib nibWithNibName:@"FilterContentView" bundle:nil] instantiateWithOwner:self options:nil] objectAtIndex:0];
        _filterView.frame = CGRectMake(0, 0, fWidth_Current, fHeight_Current);
        [_filterView.contentView drawCornerRadius:5];
        _filterView.dataIndex = index;
        _filterView.delegate = self;
        [self drawButtonWithBtn:_filterView.titleBtn];
        [self drawButtonWithBtn:_filterView.contentBtn];
        [self drawButtonWithBtn:_filterView.sourceBtn];
        [self drawButtonWithBtn:_filterView.channelBtn];
        [self drawButtonWithBtn:_filterView.typeBtn1];
        [self drawButtonWithBtn:_filterView.typeBtn2];
    }
    if (rect.origin.y < fHeight_Current/2) {
        _filterView.contentView.frame = (CGRect){10,rect.origin.y+30,_filterView.contentView.size};
        _filterView.arrowImage.image = [UIImage imageNamed:@"image_up"];
        _filterView.arrowImage.frame = (CGRect){rect.origin.x-25,rect.origin.y+15,80,60};
        
    }else {
        _filterView.contentView.frame = (CGRect){10,rect.origin.y - _filterView.contentView.size.height ,_filterView.contentView.size};
        _filterView.arrowImage.image = [UIImage imageNamed:@"image_down"];
        _filterView.arrowImage.frame = (CGRect){rect.origin.x-25,rect.origin.y-45,80,60};
    }
    [self.view addSubview:_filterView];
}
- (void)drawButtonWithBtn:(UIButton *)button
{
    [button drawCornerRadius:15];
    [button drawBorderColor:[UIColor lightGrayColor] Width:0.5];
}

#pragma mark - ContentViewDelegate
- (void)clickShieldButton:(NSInteger)index
{
    //点击 不感兴趣(确认屏蔽) 按钮
    [newsList removeObjectAtIndex:index];
    [contentTable reloadData];
    [_filterView removeFromSuperview];
    _filterView = nil;
    [self.view makeToast:@"将为你减少类似内容" position:@"center"];
    
}

#pragma mark - userAction

- (IBAction)backBtnClick:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)addBtnClick:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.selected) {
        NSArray *subAry = dataInfo[@"is_sub"];
        if (subAry.count > 0) {
            NSDictionary *item = subAry.firstObject;
            NSDictionary *params = @{@"cs_cid":[[UserEntity sharedUser] getUserID],@"cs_channelid":[dataInfo[@"channel_id"] convertToString],@"cs_id":[item[@"cs_id"] convertToString]};
            [WebService deleteMarkChannel:params WithBlock:^(id result, NSError *error) {
                if (!error) {
                    if ([result[@"errcode"] integerValue] == 0) {
                        sender.selected = !sender.selected;
                        [sender setTitle:@"订阅" forState:UIControlStateNormal];
                        [self.view makeToast:@"                 订阅成功!\n精彩内容将呈现在首页中哦~" position:@"center"];
                        NSDictionary *dict = @{@"channel_name":dataInfo[@"channel_name"],@"cs_channelid":dataInfo[@"channel_id"]};
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"deleteUserchannel" object:dict];
                    }
                }
                
            }];
        }
    }else {
        NSDictionary *params = @{@"cs_cid":[[UserEntity sharedUser] getUserID],@"cs_channelid":[dataInfo[@"channel_id"] convertToString]};
        [WebService addMarkChannel:params WithBlock:^(id result, NSError *error) {
            if (!error) {
                if ([result[@"errcode"] integerValue] == 0) {
                    sender.selected = !sender.selected;
                    [sender setTitle:@"已阅" forState:UIControlStateNormal];
                    [self.view makeToast:@"已取消订阅" position:@"center"];
                    NSDictionary *dict = @{@"channel_name":dataInfo[@"channel_name"],@"cs_channelid":dataInfo[@"channel_id"]};
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"addUserchannel" object:dict];
                }
            }
        }];
    }
}

- (IBAction)shareBtnClick:(UIButton *)sender {
    NSMutableArray *items = [NSMutableArray arrayWithObject:@"http://www.baidu.com"];
    UIActivityViewController *activity = [[UIActivityViewController alloc] initWithActivityItems:items applicationActivities:nil];
    [self presentViewController:activity animated:YES completion:nil];
}


@end
